<?php

namespace app\admin\controller\warehouse;

use app\admin\model\in\InInventory;
use app\admin\model\InventoryItemInfo;
use app\admin\model\in\InInventoryDetail;
use app\admin\model\out\OutInventory;
use app\admin\model\out\OutInventoryDetail;
use app\admin\model\inventory\InventoryDetail;
use app\common\controller\Backend;
use app\admin\model\Item;
use app\admin\model\Warehouse;
use app\admin\model\inventory\InventoryList as InventoryStorage;
use app\admin\model\GoodsItem;
use app\admin\model\out\OutboundBill;
use app\admin\model\out\OutboundBillDetail;
use app\admin\model\in\InInbound;
use app\admin\model\in\InInboundDetail;

use think\Config;
use think\Db;

/**
 * 库存一览
 * Class Inventorylist
 * @package app\admin\controller\warehouse
 */
class Inventorylist extends Backend {

  protected $model = null;
  // protected $dataLimit = 'personal';
  // protected $dataLimitField = 'uid';

  public function _initialize(){
    parent::_initialize();
    $this->model = new \app\admin\model\inventory\Lists;
  }

  /**
   * 新的库存一览表
   *
   * @return void
   */
  public function newlist(){
    $this->request->filter(['strip_tags']);
    if ($this->request->isAjax()) {

      if ($this->request->request('keyField')) {
          return $this->selectpage();
      }
      $userinfo = $this->auth->getUserInfo();
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();
      
      $this->model = new \app\admin\model\inventory\InventoryList;

      $filter = $this->request->get("filter", '');
      $filter = (array)json_decode($filter, TRUE);
      // var_dump($where);
      // die();
      /*
      $total = $this->model
          ->where($where)
          ->order($sort, $order)
          ->count();

      $list = $this->model
          ->where($where)
          ->order($sort, $order)
          ->limit($offset, $limit)
          ->select();*/
        



      $sql = 'SELECT i.id,i.itemname,i.sku,CONVERT(t.balance_count, UNSIGNED INTEGER) balance_count,g.id as goods_id,
        CONVERT(t.out_count, UNSIGNED INTEGER) out_count,CONVERT(t.in_count, UNSIGNED INTEGER) in_count,w.`name` as warehouseName
      from t_item i 
      left  JOIN t_goods g on i.sku = g.`code`
      left  join t_inventory t on t.goods_id = g.id
      left join t_warehouse w on w.`code`= t.warehouse_code where i.uid='.$userinfo['aid'];

      if(array_key_exists('sku',$filter) && $filter['sku']){
        $sql = $sql . " and i.sku= '".$filter['sku']."'";
      }

      if(array_key_exists('itemname',$filter) && $filter['itemname']){
        $sql = $sql . " and i.itemname like '%".$filter['itemname']."%'";
      }

      
      
      $list = Db::query($sql); //计算总数用的
      $total = count($list);

      if (isset($offset) && $limit){
        $sql = $sql.sprintf(' limit %s,%s',$offset,$limit);
      }
      $list = Db::query($sql);

      

      //获取最近入库，出库时间
      $InventoryDetailModel = new InventoryDetail();

      foreach ($list as $key => $value) {
        $inRecordDate = $InventoryDetailModel->where(['ref_type'=>'一件代发入库','goods_id'=>$value['goods_id']])->limit(1)->order('date_created', 'DESC')->column('date_created');
        $outRecordDate = $InventoryDetailModel->where(['ref_type'=>'一件代发出库','goods_id'=>$value['goods_id']])->limit(1)->order('date_created', 'DESC')->column('date_created');
        if($inRecordDate){
          $inRecordDate = $inRecordDate[0];
          $list[$key]['last_in_time'] = $inRecordDate;
        }
        if($outRecordDate){
          $inRecord = $outRecordDate[0];
          $list[$key]['last_out_time'] = $outRecordDate;
        }
        // $sql1 = $InventoryDetailModel->getLastSql();
        
      }

      $list = collection($list)->toArray();
      $result = array("total" => $total, "rows" => $list,"wms"=>[]);

      return json($result);
    }
    return $this->view->fetch();
  }

  public function index(){
      $this->request->filter(['strip_tags']);
      if ($this->request->isAjax()) {
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $list = collection($list)->toArray();
        $wms = $this->getWarehouse();
        //将仓库补充到 rows 数组中去
        foreach ($list as $key => $value) {
            foreach ($wms as $val) {
                if ($value['warehouseid'] == $val['code']) {
                    $list[$key]['warehouseid'] = $val['name'];
                }
            }
        }
        $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

        return json($result);
      }
      return $this->view->fetch();
  }


  public function record($ids){
    $ids = $ids ? $ids : $this->request->param("ids");
    
    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      $filter = $_GET['filter'];
      $filter = json_decode($filter,true);

      $ushortId = $this->auth->getUserInfo()['aid'];//用户id

      $itemModel = new Item;
      $itemRecord = $itemModel->get($ids);
      $InventoryDetailModel = new InventoryDetail();

      $goodsModel = new GoodsItem;
      $goods_id = $goodsModel->where(["ushortid"=>$ushortId,"code"=>$itemRecord['sku']])->value('id');


      $sort = $this->request->get("sort", "id");
      $order = $this->request->get("order", "DESC");
      $offset = $this->request->get("offset", 0);
      $limit = $this->request->get("limit", 0);

      $where = [];
      $where['goods_id'] = $goods_id;
      if(!empty($filter)){
        if(isset($filter['ref_type'])){
          if($filter['ref_type']==1){ //一件代发入库
            $filter_type = '一件代发入库';
          }

          if($filter['ref_type']==2){ //一件代发出库
            $filter_type = '一件代发出库';
          }
          $where['ref_type'] = ["eq",$filter_type];
        }

        /*
       if(isset($filter['createtime'])){
           $start = strtotime(substr($filter['createtime'],0,19));
           $end = strtotime(substr($filter['createtime'],22));
           $where['createtime'] = [">=",$start];
           //$where['createtime'] = ["<=",$end];
       }*/
      }


      $inventoryList = $InventoryDetailModel->where($where)->order($sort, $order)->limit($offset, $limit)->select();
      $total = $InventoryDetailModel->where($where)->order($sort, $order)->count();
      $list = collection($inventoryList)->toArray();
      
      $outbounBillDetail = new OutboundBillDetail();
      $outbounBill = new OutboundBill();

      $inbounBillDetail = new InInboundDetail ();
      $inbounBill = new InInbound();

      foreach ($list as $key => $value) {
        if($list[$key]['ref_type'] == '一件代发出库'){
          // $sku = $outbounBillDetail->where(['main_ref' => $list[$key]['ref_number']])->value('itemsku');
          $orderid = $outbounBill->where(['outbound_no' => $list[$key]['ref_number']])->value('orderid');
          $list[$key]['orderid'] = $orderid;
          $list[$key]['sku'] = $itemRecord['sku'];
          $list[$key]['count'] = intval($list[$key]['out_count']);
        }else if($list[$key]['ref_type'] == '一件代发入库'){
          $list[$key]['sku'] = $itemRecord['sku'];
          $list[$key]['count'] = intval($list[$key]['in_count']);
        }
      }

      $wms = $this->getWarehouse();

      $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

      return json($result);
    }
    
    $this->view->assign("ids", $ids);
    return $this->view->fetch();
    // $InventoryDetailModel = new InventoryDetail();
    // $row = $this->model->get($ids);
  }

   public function record1($ids){
       $ids = $ids ? $ids : $this->request->param("ids");
        
        $row = $this->model->get($ids);
        // $row = $this->model->get(['itemid' => $ids]);
        // $sql = $this->model::getLastSql();

       if ($this->request->isAjax()) {
           if ($this->request->request('keyField')) {
               return $this->selectpage();
           }

           $filter = $_GET['filter'];
           $filter = json_decode($filter,true);

           $ushortId = $this->auth->getUserInfo()['aid'];//用户id
           //根据产品的SKU跟uid组合得到产品的自增id
           $itemModel = new Item;
           $itemRecord = $itemModel->where(["uid"=>$ushortId,"sku"=>$row['sku']])->find();
           $where = ["itemid"=>["eq",$itemRecord['id']]];

           if(!empty($filter)){
                if(isset($filter['type'])){
                    $where['type'] = ["eq",$filter['type']];
                }
               if(isset($filter['warehouseid'])){
                   $where['warehouseid'] = ["eq",$filter['warehouseid']];
               }

               if(isset($filter['createtime'])){
                   $start = strtotime(substr($filter['createtime'],0,19));
                   $end = strtotime(substr($filter['createtime'],22));
                   $where['createtime'] = [">=",$start];
                   //$where['createtime'] = ["<=",$end];
               }
           }

            //增加搜索条件
           $sort = $this->request->get("sort", "id");
           $order = $this->request->get("order", "DESC");
           $offset = $this->request->get("offset", 0);
           $limit = $this->request->get("limit", 0);
           $itemInfo = model('InventoryItemInfo');

           $total = $itemInfo->where($where)->order($sort, $order)->count();

           $list = $itemInfo->where($where)->order($sort, $order)->limit($offset, $limit)->select();
           $sql = $itemInfo->getLastSql();

           $list = collection($list)->toArray();
           $wms = $this->getWarehouse();

           
           $outInventory = new \app\admin\model\out\Inventory;
           $inInventory =  new \app\admin\model\in\Inventory;

           //将仓库补充到 rows 数组中去
           foreach ($list as $key => $value) {
               foreach ($wms as $val) {
                  if ($value['warehouseid'] == $val['code']) {
                    $list[$key]['warehouseid'] = $val['name'];
                  }
               }
               if ( $list[$key]['type'] == 2 ) {
                $out = $outInventory->get(['outorderid' => $list[$key]['orderId']]);
                $list[$key]['status'] = $out['status'];
                $list[$key]['orderid'] = $out['orderid'];
               }elseif( $list[$key]['type'] == 1 ){
                $in = $inInventory->get(['inorderid' => $list[$key]['orderId']]);
                $list[$key]['status'] = $in['status'];
               }
               
           }
           $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

           return json($result);
       }

       $this->view->assign("ids", $ids);
       return $this->view->fetch();
   }


    /**
     * 获取仓库
     * @return array|false|\PDOStatement|string|\think\Collection
     */
   public function getWarehouse(){

       $wmsModel = model('Warehouse');
       $wms = $wmsModel->select();
       $wms = collection($wms)->toArray();

       return $wms;
   }



}
